<?php
namespace app\controller\api;
use plugin\admin\app\model\BaseConfig;
use plugin\admin\app\model\BusinessClass;
use plugin\admin\app\model\BusinessListing;
use plugin\admin\app\model\ScrollMessage;
use support\Db;
use support\Redis;
use support\Request;
use support\Response;
class MerchantController extends BaseController{
    /**
     * 获取养老院列表
     * @param Request $request
     * @return Response
     */
    public function getList(Request $request): Response
    {
        $data = $request->get();
        $page = $data['page'] ?? 1;
        $perPage = $data['perPage'] ?? 10;
        $latitude = $data['latitude'];
        $longitude = $data['longitude'];
        $radius = $data['radius'] ?? 50;
        $order = $data['order'] ?? 1; //1距离排序
        $keywords = $data['keywords'] ?? '';
        $start = ($page - 1) * $perPage;
        $items = Db::table('wa_business_listings')
            ->where(['wa_business_listings.is_settled'=>10,'wa_business_listings.status'=>'0'])
            ->leftJoin('wa_class', 'wa_business_listings.class_id', '=', 'wa_class.id')
            ->select('wa_business_listings.*','wa_class.name as class_name');
        if (isset($keywords) && $keywords){ //直接查询数据并返回
            $items = $items->where('wa_business_listings.name', 'like', '%'.$keywords.'%');
        }else{
            if ($order == 1){ //1距离排序
                $return_data = [];
                $radius = $radius*1000; // 200公里
                $locations = Redis::rawCommand('GEORADIUS', 'locations', $longitude, $latitude, $radius, 'm', 'WITHDIST', 'ASC');
                // 对商家列表进行分页
                $paginatedLocations = array_slice($locations, $start, $perPage);
                // 输出分页结果
                foreach ($paginatedLocations as $key => $location) {
                    //查询对应商家信息
                    $businessData = BusinessListing::where(['id'=>$location[0]])->first();
                    $businessData->km = self::unitConversion($location[1]);
                    $return_data[$key] = $businessData;
                }
                return Response::success($return_data);
            }else if ($order == 2){ //2 推荐排序
                $items->orderBy('wa_business_listings.sort','desc');
            }else if ($order == 3){ //3人气排序
                $items->orderBy('wa_business_listings.view','desc');
            }
        }
        $return_data =  $items->offset($start)->limit($perPage)->get();
        foreach ($return_data as $key => &$val){
            // 获取当前养老院和用户的距离
            $km = self::GetDistance($latitude, $longitude, $val->latitude, $val->longitude, 1 , 2);
            $val->km = self::unitConversion($km);
        }
        return Response::success($return_data);
    }
    /**
     * 计算两组经纬度坐标 之间的距离
     * params ：lat1 纬度1； lng1 经度1； lat2 纬度2； lng2 经度2； len_type （1:m or 2:km);
     * return m or km
     */
    public static function GetDistance($lat1, $lng1, $lat2, $lng2, $len_type = 1, $decimal = 2): float
    {
        $lat1 = floatval($lat1);
        $lng1 = floatval($lng1);
        $lat2 = floatval($lat2);
        $lng2 = floatval($lng2);
        $pi = 3.1415926;
        $radius = 6378.137;
        $radLat1 = $lat1 * $pi / 180.0;
        $radLat2 = $lat2 * $pi / 180.0;
        $a = $radLat1 - $radLat2;
        $b = ($lng1 * $pi / 180.0) - ($lng2 * $pi / 180.0);
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
        $s = $s * $radius;
        $s = round($s * 1000);
        if ($len_type > 1) {
            $s /= 1000;
        }
        return round($s, $decimal);
    }
    /**
     *距离转换
     * @param int $mileage
     * @return string
     */
    public static function unitConversion($mileage = 0): string
    {
        if ($mileage < '1000'){
            $distanceInKilometers = round($mileage).'m';
        }else{
            $distanceInKilometers = round($mileage / 1000, 2).'km';
        }
        return $distanceInKilometers;
    }

    /**
     * 获取滚动消息
     * @param Request $request
     * @return Response
     */
    public function getRollMsg(Request $request): Response
    {
        $list = ScrollMessage::where(['status'=>0])->orderBy('sort', 'desc')->get();
        return Response::success($list);
    }

    /**
     * 获取分类列表
     * @param Request $request
     * @return Response
     */
    public function getCategoryList(Request $request): Response
    {
        // 查询当前表的分类
        $categories = BusinessClass::where('status', 0)->get();
        // 生成以 id 为键的分类数组
        $categoryMap = [];
        foreach ($categories as $category) {
            $category->children = [];
            $categoryMap[$category->id] = $category;
        }
        // 生成 children
        $rootCategories = [];
        foreach ($categoryMap as $category) {
            if ($category->pid == 0) {
                $rootCategories[] = $category;
            } else {
                if (isset($categoryMap[$category->pid])) {
                    $parent = $categoryMap[$category->pid];
                    $children = $parent->children;
                    $children[] = $category;
                    $parent->children = $children;
                    $categoryMap[$category->pid] = $parent;
                }
            }
        }
        return Response::success($rootCategories);
    }

    /**
     * 帮助文档
     * @return Response
     */
    public function getHelpContent(): Response
    {
        $list = BaseConfig::where(['status'=>0,'type'=>'1'])->first();
        return Response::success($list);
    }
}